import hashlib, os, base64, gzip
import dbEngine, cipherEngine

class FileProc:
    def __init__(self,key):
        self.db = dbEngine.DBEngine()
        self.cipher = cipherEngine.CipherEngine(key,self.db)
        self.db.setCipher(self.cipher)
    def __hash(self,data):
        return hashlib.md5(data).hexdigest()
    
    def list(self):
        self.db.connect()
        c = db.getFiles()
        for row in c:
            print row[0]
        self.db.disconnect()

    def put(self,filename):
        self.db.connect()
        path = filename
        if not os.path.isfile("%s" %path):
            path = "%s\%s" %(os.getcwd(),filename)
            if not os.path.isfile("%s"%path):
                return False
        information = {"filename":"","hash":"","IV":""}
        with open(path,"rb") as f:
            data = f.read()
        information['filename'] = filename
        information['hash'] = self.__hash(data)
        IV, ob = self.cipher.encrypt(data,filename)
        ob = base64.encodestring(ob)
        information['IV'] = IV
        with gzip.open("%s/%s.dsx" %(os.getcwd(),information['hash']), 'wb') as f:
            f.write(ob)
        os.remove(path)
        if self.db.getHash(filename):
            self.db.updateHash(information)
        else:
            self.db.insert(information)
        self.db.disconnect()
        return information
    
    def get(self,filename):
        self.db.connect()
        h = self.db.getHash(filename)
        
        if os.path.exists("%s/%s.dsx"%(os.getcwd(),h)):
            ob = ''
            with gzip.open("%s/%s.dsx" %(os.getcwd(),h), 'rb') as f:
                ob = f.read()
            ob = base64.decodestring(ob)
            data = self.cipher.decrypt(ob,filename)
            self.db.disconnect()
            if self.__hash(data) == h:
                with open("%s/%s" %(os.getcwd(),filename), "wb") as f:
                    f.write(data)
                return True
            else:
                return False